package br.com.hstar.server.cliente;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.validator.GenericValidator;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.hstar.client.cliente.tipocliente.TipoClienteService;
import br.com.hstar.client.cliente.tipocliente.TipoClienteUI;
import br.com.hstar.client.util.HstarUserException;
import br.com.hstar.model.cliente.TipoClienteDO;
import br.com.hstar.server.DozerHelper;
import br.com.hstar.server.DozerUtility;
import br.com.hstar.server.HibernateUtility;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TipoClienteServiceImpl extends RemoteServiceServlet implements TipoClienteService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8898822652463873329L;

	public void saveOrUpdate(TipoClienteUI objUI) throws HstarUserException {
		TipoClienteDO objDO = (TipoClienteDO) DozerUtility.getMapper().map(objUI, TipoClienteDO.class);
		
		if(GenericValidator.isBlankOrNull(objDO.getDescricao()))
			throw new HstarUserException("O nome do tipo não pode ser vazio");
		
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();
		
		if(objUI.getId() != null) {
			sessao.update(objDO);
		} else {
			sessao.save(objDO);
		}

		transaction.commit();
		sessao.close();
	}
	
	public List listAll() {
		Session sessao = HibernateUtility.getSession();
		Criteria select = sessao.createCriteria(TipoClienteDO.class);
		ArrayList objetos = (ArrayList)select.list();
		sessao.close();
		
		return DozerHelper.mapList(
				DozerUtility.getMapper(), 
				objetos, 
				TipoClienteUI.class);
	}
	
	public TipoClienteUI retrieveById(Long id) {
		Session sessao = HibernateUtility.getSession();
		Criteria cri = sessao.createCriteria(TipoClienteDO.class);
		cri.add(Restrictions.eq("id", id));
		TipoClienteDO objDO = (TipoClienteDO) cri.uniqueResult();
		sessao.close();
				
		TipoClienteUI objUI = (TipoClienteUI) DozerUtility.getMapper().map(objDO, TipoClienteUI.class);
		
	  	return objUI;
	}
	
	public void delete(Long id) {
		Session sessao = HibernateUtility.getSession();
		Transaction transaction = sessao.beginTransaction();

			Criteria cri = sessao.createCriteria(TipoClienteDO.class);
			cri.add(Restrictions.eq("id", id));
			TipoClienteDO objDO = (TipoClienteDO) cri.uniqueResult();
			sessao.delete(objDO);

		transaction.commit();
		sessao.close();
	}
}
